﻿using ZR.Admin.WebApi.Filters;
using ZR.Model;
using ZR.ServiceCore.Model;
using ZR.ServiceCore.Model.Dto;
using ZR.ServiceCore.Services.IService;

namespace ZR.Admin.WebApi.Controllers.System;

[Verify]
[Route("system/field")]
public class SysFieldController : BaseController
{
    private readonly ISysFieldService _sysFieldService;
    private readonly ISysRoleFieldService _sysRoleFieldService;
    
    public SysFieldController(ISysFieldService sysFieldService, ISysRoleFieldService sysRoleFieldService)
    {
        _sysFieldService = sysFieldService;
        _sysRoleFieldService = sysRoleFieldService;
    }

    [HttpGet("getModelList")]
    public async Task<IActionResult> GetModelList([FromQuery] PagerInfo pagerInfo)
        => SUCCESS(await _sysFieldService.GetModelList(pagerInfo));

    [HttpGet("getFields")]
    public async Task<IActionResult> GetFields([FromQuery] string fullName, long roleId)
        => SUCCESS(await _sysFieldService.GetFields(fullName, roleId));

    [HttpPost("initFields")]
    public async Task<IActionResult> InitFields()
        => SUCCESS(await _sysFieldService.InitFields());

    [HttpPut("addOrUpdateSysRoleField/{roleId}")]
    public async Task<IActionResult> AddOrUpdateSysRoleField([FromBody] List<SysFieldDto> sysFieldDtos,
        [FromRoute] long roleId)
        => SUCCESS(await _sysRoleFieldService.InsertOrUpdateSysRoleField(sysFieldDtos, roleId));

    [HttpPost("fieldDisplay")]
    public async Task<IActionResult> FieldDisplay(string blockCode)
    {
        var info = JwtUtil.GetLoginUser(HttpContext);
        var roleIds = info.Roles.Select(it => it.RoleId).ToList();
        var list = await _sysFieldService.Queryable()
            .LeftJoin<SysFieldBlock>((sf, sfb) => sf.Id == sfb.FieldId)
            .LeftJoin<SysBlock>((sf, sfb, sb) => sfb.BlockId == sb.Id )
            .LeftJoin<SysRoleField>((sf,sfb, sb, srf) => sf.Id == srf.FieldId)
            .Where((sf,sfb, sb, srf) => roleIds.Contains(srf.RoleId))
            .Where((sf,sfb, sb, srf) => sb.Code == blockCode)
            .WithCache(10 * 60)
            .Select((sf,sfb, sb, srf) => sf.FieldName)
            .ToListAsync();
        // var list = await _sysFieldService.Queryable()
        //     .LeftJoin<SysRoleField>((sf, srf) => sf.Id == srf.FieldId)
        //     .Where((sf, srf) => roleIds.Contains(srf.RoleId))
        //     .WithCache(10 * 60)
        //     .Select((sf, srf) => sf.FieldName)
        //     .ToListAsync();
        return SUCCESS(list);
    }
    
}